<?php

session_start();

header('Access-Control-Allow-Origin:*');

date_default_timezone_set("PRC");

header("Content-Type: text/html;charset=utf8");

require_once '../common/in_mysql.php';
require_once '../db/bbs.db.php';

$action = filter_input(INPUT_POST, "action") ? filter_input(INPUT_POST, "action") : filter_input(INPUT_GET, "action");

$res = array();
switch ($action) {
    case 'listBbs':
        $res = listBbs();
        break;
    case 'addBbs':
        $res = addBbs();
        break;
    case 'editBbs':
        $res = editBbs();
        break;
    case 'deleteBbs':
        $res = deleteBbs();
        break;
    case 'topBbs':
        $res = topBbs();
        break;
    default :
}
echo json_encode($res);

function listBbs() {
    $type = filter_input(INPUT_POST, "type");    
    $res['code'] = 0;
    $res['msg'] = "";
    $bbsDb = new BbsDb();
    $bbsList = $bbsDb->listBbs($type);

    $res['data'] = $bbsList;
    $res['count'] = count($bbsList);
    return $res;
}

function addBbs() {
    $title = filter_input(INPUT_POST, "title");
    $content = filter_input(INPUT_POST, "content");
    $type = filter_input(INPUT_POST, "type");

    if (trim($title) == "") {
        $res['code'] = 233;
        $res['msg'] = "请输入名称";
        return $res;
    }

    $bbsDb = new BbsDb();

    if ($bbsDb->addBbs($content, $title, $type)) {
        $res['code'] = 0;
        $res['msg'] = "";
    } else {
        $res['code'] = 230;
        $res['msg'] = "添加公告信息失败";
    }
    return $res;
}

function editBbs() {
    $id = filter_input(INPUT_POST, "id");
    $title = filter_input(INPUT_POST, "title");
    $content = filter_input(INPUT_POST, "content");
    $type = filter_input(INPUT_POST, "type");

    if (trim($title) == "") {
        $res['code'] = 233;
        $res['msg'] = "请输入名称";
        return $res;
    }

    $bbsDb = new BbsDb();

    if ($bbsDb->editBbs($id, $content, $title, $type)) {
        $res['code'] = 0;
        $res['msg'] = "";
    } else {
        $res['code'] = 232;
        $res['msg'] = "编辑公告信息失败";
    }
    return $res;
}

function deleteBbs() {
    $id = filter_input(INPUT_POST, "id");
    $bbsDb = new BbsDb();

    if ($bbsDb->deleteBbs($id)) {
        $res['code'] = 0;
        $res['msg'] = "";
    } else {
        $res['code'] = 236;
        $res['msg'] = "删除公告信息失败";
    }
    return $res;
}

function topBbs() {
    $id = filter_input(INPUT_POST, "id");
    $top = filter_input(INPUT_POST, "top");
    $bbsDb = new BbsDb();

    if ($bbsDb->topBbs($id, $top)) {
        $res['code'] = 0;
        $res['msg'] = "";
    } else {
        $res['code'] = 236;
        $res['msg'] = "置顶公告信息失败";
    }
    return $res;
}